<!-- 点菜 – 选择菜谱组件 - 快捷点餐 - 弹窗组件 -->
<template>
  <div>
    <custom-dialog v-model:visible="dialogVisible" top="2vh" curent-class="food-cookbook-dialog">
      <div class="content-box">
        <div class="dialog-title">快捷点单</div>
        <div class="food-box">
          <div class="left-box">
            <div class="search-wrap">
              <el-select
                v-model="menuListPageQuery.category_id"
                placeholder="请选择菜谱分类"
                clearable
                size="small"
                class="my-select"
                @change="onSearch"
              >
                <el-option
                  v-for="item in menuCateList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <div class="search-input-box">
                <img class="search-icon" src="@/assets/images/home/search-icon.png" alt="" />
                <input
                  class="input"
                  v-model="menuListPageQuery.search"
                  type="text"
                  placeholder="请输入订单号或菜谱名称查询"
                  @input="onSearch"
                />
              </div>
              <div class="search-btn" @click="handleSearch">搜索</div>
            </div>
            <div class="table-box" v-loading="menuListLoading">
              <el-table
                :data="menuList"
                style="width: 100%"
                height="2.5rem"
                @row-click="handleRowClick"
                :row-class-name="tableRowClassName"
              >
                <el-table-column label="" width="30">
                  <template #default="scope">
                    <el-radio
                      class="radio"
                      v-model="templateSelection"
                      :label="scope.row.id"
                    ></el-radio>
                    <span> </span>
                  </template>
                </el-table-column>
                <el-table-column align="center" show-overflow-tooltip prop="id" label="ID">
                </el-table-column>
                <el-table-column align="center" show-overflow-tooltip prop="name" label="菜谱名称">
                </el-table-column>
                <el-table-column align="center" show-overflow-tooltip label="菜谱分类">
                  <template #default="scope">
                    <span>{{ scope.row.category.name }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="pagination-box" v-if="pageListTotal > 0">
              <Pagination
                :total="pageListTotal"
                v-model:page="menuListPageQuery.page"
                v-model:limit="menuListPageQuery.limit"
                @pagination="handlePagination"
              />
            </div>
          </div>
          <div class="right-box">
            <div class="scroll-list" v-loading="foodListLoading">
              <div class="scroll-item-wrap" v-if="!showNoData">
                <div
                  class="scroll-item"
                  v-for="food in foodList"
                  :key="food.id"
                  @click="handleSelectFood(food)"
                >
                  <img
                    class="image"
                    v-if="food?.foodInfo?.images && food.foodInfo.images.length"
                    :src="food.foodInfo.images[0].file.preview_url"
                    alt=""
                  />
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="food.foodInfo.name"
                    placement="top"
                  >
                    <div class="name">{{ food.foodInfo.name }}</div>
                  </el-tooltip>
                  <div
                    class="vip-money"
                    v-if="
                      food.skuList &&
                      currentDesktopDiscountInfo &&
                      currentDesktopDiscountInfo.is_vip_price === 1 &&
                      orderFoodPageType === 'desktopPage'
                    "
                  >
                    ￥{{ food.member_price }}/{{ food.unit }}
                  </div>
                  <div class="count" v-else>￥{{ food.price }}/{{ food.unit }}</div>
                  <!-- 已售罄 -->
                  <div class="soldout-img-box" v-if="food.foodInfo.num === 0">
                    <img class="soldout-img" src="@/assets/images/home/yishouqing-icon.png" alt="" />
                  </div>
                  <!-- 显示选中菜品的图标 -->
                  <img
                    v-show="food.isChecked"
                    class="choose-img"
                    src="@/assets/images/home/xuanzhongzhuotai.png"
                    alt=""
                  />
                </div>
              </div>
              <!-- 暂无数据的组件 -->
              <div class="no-data-box" v-else>
                <NotData desc="暂无菜品数据" />
              </div>
            </div>
          </div>
        </div>
        <div class="footer-btn">
          <div class="cancel-btn" @click="onCancel">取消</div>
          <div class="confirm-btn" @click="onConfirm">确定</div>
        </div>
      </div>
    </custom-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import CustomDialog from '@/components/CustomDialog/Index.vue'
import Pagination from '@/components/Pagination/Index.vue'
import NotData from '@/components/NotData/Index.vue'
import { fetchMenuList, menuCategoryList, menuFoodList } from '@/api/food'

interface Category {
  id: number
  name: string
}

interface FoodInfo {
  id: number
  name: string
  num: number
  images?: Array<{
    file: {
      preview_url: string
    }
  }>
}

interface FoodSku {
  id: number
  price: number
  member_price?: number
  unit: string
}

interface MenuFood {
  id: number
  foodInfo: FoodInfo
  skuList?: FoodSku[]
  price: number
  member_price?: number
  unit: string
  isChecked?: boolean
}

interface Menu {
  id: number
  name: string
  category: Category
  menu_detail?: MenuFood[]
}

interface MenuListPageQuery {
  page: number
  limit: number
  search: string
  category_id: number | null
}

const props = defineProps<{
  visible: boolean
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'confirm', foods: MenuFood[]): void
}>()

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (val: boolean) => emit('update:visible', val)
})

// 菜谱查询数据相关
const menuListPageQuery = ref<MenuListPageQuery>({
  page: 1,
  limit: 10,
  search: '',
  category_id: null
})

// 菜谱列表总条数
const pageListTotal = ref(0)
// 菜谱分类列表
const menuCateList = ref<Category[]>([])
// 菜谱列表
const menuList = ref<Menu[]>([])
// 菜品列表
const foodList = ref<MenuFood[]>([])
// 是否显示暂无数据
const showNoData = ref(false)
// 选中菜品的数组集合
const selectedActiveFoodList = ref<MenuFood[]>([])
// 选中当行表格数据
const templateSelection = ref<number | null>(null)
// 菜谱列表加载状态
const menuListLoading = ref(false)
// 菜品列表加载状态
const foodListLoading = ref(false)

// 模拟store数据，实际项目中应该从store获取
const currentDesktopDiscountInfo = ref({
  is_vip_price: 0
})
const orderFoodPageType = ref('desktopPage')

// 获取菜谱分类
const getMenuCategoryList = async () => {
  try {
    const res = await menuCategoryList({})
    if (res?.status === 200) {
      menuCateList.value = res.data || []
    }
  } catch (e) {
    ElMessage.error('获取菜谱分类失败')
  }
}

// 获取菜谱列表
const getMenuList = async (page?: number, limit?: number) => {
  try {
    menuListLoading.value = true
    const params = {
      ...menuListPageQuery.value,
      ...(page && { page }),
      ...(limit && { limit })
    }
    const res = await fetchMenuList(params)
    if (res?.status === 200) {
      menuList.value = res.data?.data || []
      pageListTotal.value = res.data?.total || 0
    }
  } catch (e) {
    ElMessage.error('获取菜谱列表失败')
  } finally {
    menuListLoading.value = false
  }
}

// 获取菜谱下面的菜品列表
const getMenuFoodList = async (id: number) => {
  try {
    foodListLoading.value = true
    const res = await menuFoodList({ menu_id: id })
    if (res?.status === 200) {
      selectedActiveFoodList.value = []
      foodList.value = res.data || []
      foodList.value.forEach(item => {
        if (item.foodInfo.num !== 0) {
          item.isChecked = true
          // 全部选中菜品
          getSelectAllFood(item)
        }
      })
      showNoData.value = (res.data || []).length === 0
    }
  } catch (e) {
    ElMessage.error('获取菜谱菜品失败')
  } finally {
    foodListLoading.value = false
  }
}

// 点击对应的表格当前行,获取菜谱下面对应的菜品
const handleRowClick = (row: Menu) => {
  templateSelection.value = row.id
  getMenuFoodList(row.id)
}

// 选中对应的菜品,取消选中和选中的状态
const handleSelectFood = (food: MenuFood) => {
  const activeIndex = selectedActiveFoodList.value.findIndex(item => item.id === food.id)
  if (activeIndex === -1) {
    food.isChecked = true
    const foodData = {
      ...food,
      // 菜品名称
      foodName: food.foodInfo.name,
      // 选中的对应规格：单规格取skuList的第一项
      food_sku_id: food.id ? food.id : 0, // 菜品sku_id
      foodNum: 1, // 数量
      discount: 10, // 菜品单独折扣范围1-10 ， 10为不打折
      // 判断是否使用了单菜折扣
      isUseSingleFoodDiscount: false,
      foodPrice: food.price, // 菜品原价
      foodTotalPrice: food.price, // 菜品总价
      is_write_food: 0, // 0:不是手写菜品  1：是手写菜品
      write_food_name: '', // 手写菜品名称
      write_food_price: 0, // 手写菜品价格
      making_ids: [], // 做法ID  数组
      write_making: [], // 手写做法名称集合
      taste_ids: [], // 口味列表ID  数组
      write_taste: [], // 手写口味名称集合
      position: [], // 部位名称集合
      is_present: 0 // 1:赠送   0：非赠送
    }
    selectedActiveFoodList.value.push(foodData as MenuFood)
  } else {
    food.isChecked = false
    selectedActiveFoodList.value.splice(activeIndex, 1)
  }
}

// 全部选中菜品  【菜谱里面只有单规格的菜品】
const getSelectAllFood = (food: MenuFood) => {
  const foodData = {
    ...food,
    // 菜品名称
    foodName: food.foodInfo.name,
    // 选中的对应规格：单规格取skuList的第一项
    food_sku_id: food.id ? food.id : 0, // 菜品sku_id
    foodNum: 1, // 数量
    discount: 10, // 菜品单独折扣范围1-10 ， 10为不打折
    // 判断是否使用了单菜折扣
    isUseSingleFoodDiscount: false,
    foodPrice: food.price, // 菜品原价
    foodTotalPrice: food.price, // 菜品总价
    foodUnit: food.unit, // 菜品单位
    num: food.foodInfo.num
  }
  // 判断是否是绑定了会员，显示对应的会员价
  if (
    currentDesktopDiscountInfo.value &&
    currentDesktopDiscountInfo.value?.is_vip_price === 1 &&
    orderFoodPageType.value === 'desktopPage'
  ) {
    ;(foodData as any).memberPrice = food.member_price
    ;(foodData as any).foodTotalMemberPrice = food.member_price
  }
  selectedActiveFoodList.value.push(foodData as MenuFood)
}

// 确认提交事件,单规格商品专用
const onConfirm = () => {
  if (selectedActiveFoodList.value.length === 0) {
    ElMessage.warning('请先选择菜品')
    return
  }
  
  emit('confirm', selectedActiveFoodList.value)
  dialogVisible.value = false
  resetFormData()
}

// 取消事件
const onCancel = () => {
  dialogVisible.value = false
  resetFormData()
}

// 重置数据
const resetFormData = () => {
  foodList.value = []
  showNoData.value = true
  selectedActiveFoodList.value = []
  templateSelection.value = null
  menuListPageQuery.value = {
    page: 1,
    limit: 10,
    search: '',
    category_id: null
  }
}

// 设置对应行数的背景颜色
const tableRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  if (rowIndex % 2 === 0) {
    // 偶数
    return 'warning-row'
  } else if (rowIndex % 2 !== 0) {
    // 奇数
    return 'success-row'
  }
  return ''
}

// 搜索
const handleSearch = () => {
  menuListPageQuery.value.page = 1
  getMenuList()
  showNoData.value = true
}

// 搜索操作
const onSearch = () => {
  menuListPageQuery.value.page = 1
  getMenuList()
  showNoData.value = true
}

// 分页处理
const handlePagination = (page: number, limit: number) => {
  menuListPageQuery.value.page = page
  menuListPageQuery.value.limit = limit
  getMenuList(page, limit)
}

// 监听弹窗显示状态
watch(dialogVisible, (val) => {
  if (val) {
    // 获取菜谱分类
    getMenuCategoryList()
    // 获取菜谱列表
    getMenuList()
  }
})
</script>

<style scoped lang="scss">
.content-box {
  max-height: 786px;
  overflow: hidden;

  .dialog-title {
    height: 67px;
    line-height: 67px;
    font-size: 20px;
    font-family: PingFang SC, PingFang SC-Bold;
    font-weight: 700;
    text-align: center;
    color: #333333;
    border-radius: 20px 20px 0 0;
    border-bottom: 1px solid #f2f2f2;
    margin-bottom: 20px;
  }

  .food-box {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    height: 600px;

    .left-box {
      width: 670px;
      
      .search-wrap {
        display: flex;
        // grid-template-columns: repeat(3, 1fr);
        gap: 20px;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;

        .search-input-box {
          width: 348px;
          height: 40px;
          border: 1px solid #d2d2d2;
          border-radius: 10px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          padding-left: 20px;
          
          .search-icon {
            flex-shrink: 0;
            width: 24px;
            height: 24px;
          }
          
          .input {
            border: none;
            outline: none;
            width: 300px;
            font-size: 16px;
            font-family: PingFang SC, PingFang SC-Regular;
            font-weight: 400;
            text-align: left;
            color: #333333;
            margin-left: 10px;
          }
        }
        
        .search-btn {
          width: 90px;
          height: 38px;
          flex-shrink: 0;
          border: 1px solid #7c0a03;
          border-radius: 10px;
          line-height: 40px;
          font-size: 16px;
          font-family: PingFang SC, PingFang SC-Regular;
          font-weight: 400;
          text-align: center;
          color: #7c0a03;
          cursor: pointer;
        }
      }

      .table-box {
        height: 500px;
        overflow: hidden;
      }

      .pagination-box {
        margin-top: 20px;
        
        .pagination {
          width: 670px;
        }
      }
    }

    .right-box {
      width: 700px;
      
      .scroll-list {
        position: relative;
        box-sizing: border-box;
        height: 600px;
        width: 700px;
        background: #f8f8f8;
        padding: 20px;
        overflow-y: auto;
        border-radius: 12px;
        
        .scroll-item-wrap {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 20px;
          align-items: center;
          flex-wrap: wrap;
          width: 100%;
          
          .scroll-item {
            position: relative;
            box-sizing: border-box;
            width: 150px;
            height: 184px;
            border-radius: 12px;
            // margin-top: 20px;
            cursor: pointer;
            background: #ffffff;
            // margin-right: 20px;
            
            .image {
              flex-shrink: 0;
              width: 150px;
              height: 112px;
              border-radius: 12px 12px 0 0;
            }
            
            .name {
              font-size: 18px;
              font-family: PingFang SC, PingFang SC-Bold;
              font-weight: 700;
              text-align: left;
              color: #131432;
              padding-left: 10px;
              margin-top: 10px;
              max-width: 150px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            
            .count {
              padding-left: 10px;
              margin-top: 10px;
              font-size: 14px;
              font-family: PingFang SC, PingFang SC-Regular;
              font-weight: 400;
              text-align: left;
              color: #333333;
            }
            
            .vip-money {
              padding-left: 10px;
              margin-top: 10px;
              font-size: 14px;
              font-family: PingFang SC, PingFang SC-Regular;
              font-weight: 400;
              text-align: left;
              color: #efc291;
            }
            
            .soldout-img-box {
              position: absolute;
              top: 0;
              left: 0;
              width: 150px;
              height: 184px;
              background: rgba(0, 0, 0, 0.5);
              border-radius: 12px;
              z-index: 1;
              
              .soldout-img {
                position: absolute;
                top: 34px;
                left: 4px;
                width: 142px;
                height: 117px;
                z-index: 2;
              }
            }
            
            .choose-img {
              position: absolute;
              right: 12px;
              bottom: 12px;
              width: 24px;
              height: 24px;
            }
          }
          
          .scroll-item:nth-child(4n) {
            margin-right: 0;
          }
        }
      }
    }
  }

  .footer-btn {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border-top: 1px solid #e8e8e8;
    padding-top: 20px;
    
    .cancel-btn {
      width: 92px;
      height: 48px;
      background: #ffffff;
      border: 1px solid #333333;
      border-radius: 10px;
      font-size: 16px;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #333333;
      line-height: 48px;
      cursor: pointer;
      margin-right: 20px;
    }
    
    .confirm-btn {
      width: 92px;
      height: 48px;
      background: #7c0a03;
      border-radius: 10px;
      font-size: 16px;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #ffffff;
      line-height: 48px;
      cursor: pointer;
    }
  }
}

.no-data-box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  margin-top: 200px;
}

/* 滚动条整体的大小 */
.scroll-list::-webkit-scrollbar {
  width: 6px !important;
  height: 0 !important;
}
/* 滚动条里滑动的滑块 */
.scroll-list::-webkit-scrollbar-thumb {
  height: 200px !important;
  background: #d2d2d2 !important;
  border-radius: 3px !important;
}
/* 滚动条底层样式 */
.scroll-list::-webkit-scrollbar-track {
  display: none !important;
}
</style>

<style lang="scss">
.food-cookbook-dialog {
  max-height: unset !important;
  min-width: 1460px !important;
  width: 1460px !important;
}

:deep(.my-select) {
  width: 178px;
  /* selecte 框的高度设置，默认是 40px*/
  .el-input__inner {
    height: 46px;
  }
  /* 下面设置右侧按钮居中 */
  .el-input__suffix {
    top: 16px;
  }
  .el-input__icon {
    line-height: inherit;
  }
  .el-input__suffix-inner {
    display: inline-block;
  }
}
//单选框选中的颜色
:deep(.el-radio__input.is-checked .el-radio__inner) {
  border-color: #7c0a03;
  background: #7c0a03;
}

:deep(.el-table .warning-row) {
  background: #ffffff;
}

:deep(.el-table .success-row) {
  background: #f8f8f8;
}
:deep(.el-table::before) {
  content: '';
  position: absolute;
  background-color: transparent !important;
  z-index: 1;
}
:deep(.el-table__body-wrapper) {
  height: 600px;
  overflow-y: auto;
}
//滚动条整体的大小
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px !important;
  height: 0 !important;
}
//滚动条里滑动的滑块
:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  height: 200px !important;
  background: #d2d2d2 !important;
  border-radius: 3px !important;
}
//滚动条底层样式
:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  display: none !important;
}
:deep(.el-table th.el-table__cell) {
  background: #a85b62;
  color: #fff !important;
}
:deep(.el-table td.el-table__cell) {
  border: none !important;
}
</style>
